package airacrobats.error;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 * This class handles errors.
 */
public class ErrorHandler implements Thread.UncaughtExceptionHandler
{
    /**
     * Flag that indicates if an error has already been shown.
     */
    private static boolean done;
    
    /**
     */
    public void uncaughtException(Thread t, Throwable e)
    {
        if (done)
            return;

        done = true;
        
        File file = new File("Error.log");
        boolean firstAppend = !file.exists();

        try
        {
            DataOutputStream output = new DataOutputStream(new FileOutputStream(file, true));

            if (!firstAppend)
                output.writeBytes("\n");

            output.writeBytes("Exception thrown on " + new Date(System.currentTimeMillis()).toString()
                    + "\nCauses:\n");
            output.writeBytes(e.toString() + "\n");

            for (StackTraceElement element : e.getStackTrace())
            {
                output.writeBytes(element.toString() + "\n");
            }
            
            output.close();
        }
        catch (Exception ex)
        {
            // Do nothing about it.
        }

        e.printStackTrace();
        
        showError();
    }

    /**
     * Shows the error dialog.
     */
    private void showError()
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JOptionPane.showMessageDialog(null, "An exception was thrown. More details were "
                        + "written on the error log file.", "Error", JOptionPane.ERROR_MESSAGE);
                System.exit(-1);
            }
        });
    }
}
